/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.nio.http.server.builtin;

import cn.hermit.nio.http.Http;
import cn.hermit.nio.http.server.HttpRequest;
import cn.hermit.util.IOUtils;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 2/6/2017
 */
public class JavaHttpRequest extends HttpRequest {

    private HttpExchange httpExchange;

    public JavaHttpRequest(HttpExchange httpExchange) {
        this.httpExchange = httpExchange;
        requestURI = httpExchange.getRequestURI().getPath();
        verb = Http.Verb.valueOf(httpExchange.getRequestMethod());
        version = Version.HTTP11;

        Headers headers = httpExchange.getRequestHeaders();
        for(String name : headers.keySet()) {
            List<String> val = headers.get(name);
            if(val == null || val.size() == 0) {
                headerMap.put(name, "");
            } else {
                String valStr = val.get(0);
                for(int i = 1; i < val.size(); i++) {
                    valStr = valStr + "," + val.get(i);
                }
                headerMap.put(name, valStr);
            }
        }
        InputStream is = null;
        try {
            is = httpExchange.getRequestBody();
            body = IOUtils.inputStream2ByteArray(is, false);
        } catch (IOException e) {
            //ignored
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    //ignored
                }
            }
        }
    }

    @Override
    public String getRequestURI() {
        return super.getRequestURI();
    }

    @Override
    public Verb getVerb() {
        return super.getVerb();
    }

    @Override
    public Version getVersion() {
        return super.getVersion();
    }

    @Override
    public String getHeader(String name) {
        return super.getHeader(name);
    }

    @Override
    public void setHeader(String name, String value) {
        super.setHeader(name, value);
    }

    @Override
    public String getQueryParameter(String name) {
        return super.getQueryParameter(name);
    }

    @Override
    public String getFormParameter(String name) {
        return super.getFormParameter(name);
    }

    @Override
    public byte[] getBody() {
        return super.getBody();
    }
}
